// TODO: make sure use right login component
// import { MultiLogin } from 'leihuo-h-multi-login'
import store from '@/store/index'
import { showToast } from '@/common/utils/toast'
import * as Types from '@/store/mutation-types'
import config from '@/config'

const NOT_LOGIN = 2
export default {
  init () {
    return new Promise((resolve, reject) => {
      // eslint-disable-next-line
      const multiLogin = (this.multiLogin = MultiLogin.getInstance({
        activityName: config.activityName,
        loginParams: {
          loginType: 'common',
          showExtra: true
        },
        onSuccess: (loginInfo) => {
          store.commit(Types.SET_MUTI_LOGIN_INFO, loginInfo)
          store.dispatch('fetchUserInfo').catch((err) => {
            multiLogin.logout(() => {
              if (err.code !== NOT_LOGIN) {
                showToast(err.message)
              }
            })
          })
          resolve(loginInfo)
        },
        onError: (err) => {
          store.commit(Types.SET_MUTI_LOGIN_INFO, null)
          store.dispatch('fetchUserInfo').catch(() => {})
          reject(err)
        }
      }))
    })
  },

  login (cb, loginInfoCB) {
    if (!this.multiLogin) return
    this.multiLogin.login({
      onSuccess: async (loginInfo) => {
        store.commit(Types.SET_MUTI_LOGIN_INFO, loginInfo)
        store
          .dispatch('fetchUserInfo')
          .then((res) => {
            console.log('res1', res)
            if (loginInfoCB) {
              loginInfoCB(res)
            }
          })
          .catch((err) => {
            if (loginInfo.urs.indexOf('@') > -1 && err.code === NOT_LOGIN) {
              this.multiLogin.logout(() => {
                store.commit(Types.SET_MUTI_LOGIN_INFO, null)
              })
            }
          })
        if (typeof cb === 'function') {
          cb()
        }
      }
    })
  },

  logout (cb) {
    if (!this.multiLogin) {
      return
    }
    if (cb) {
      this.multiLogin.logout(() => {
        store.commit(Types.SET_MUTI_LOGIN_INFO, null)
        store.dispatch('fetchUserInfo').catch(() => {})
        cb && cb()
      })
    } else {
      this.multiLogin.logout()
    }
  }
}
